import Axios from "axios";
import { Message } from 'element-ui';

const request = Axios.create({
    baseURL: "/api",
    timeout: 30000,
    headers: { "Content-Type": "application/json" }
});

// 请求拦截器：在请求头中添加 JWT
request.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 接口响应拦截
request.interceptors.response.use((response) => {
    if (response.data.code === 401) {
        // 移除 localStorage 中的 JWT
        localStorage.removeItem('token');
        window.location.href = "/#/login";
        return new Promise(() => { });
    }
    return response;
}, (error) => {
    console.log(error);
    Message.error(error.message || '请求发生错误');
    return Promise.reject(error);
});

export default request;    